// 搜索引擎管理相关功能

// 全局变量
var searchEngines = [];
var currentSearchEngineId = null;
var dropdownVisible = false;
const STORAGE_KEY = 'selectedSearchEngineId'; // 统一存储键名

/**
 * 加载搜索引擎列表
 * @returns {Promise<Array>} 搜索引擎列表
 */
async function loadSearchEngines() {

    try {
        const response = await fetch('/api/public/search-engines');

        
        if (response.ok) {
            const data = await response.json();
    
            
            // 验证返回数据的格式
            if (!Array.isArray(data)) {
    
                return [];
            }
            
            searchEngines = data;
    
            
            // 如果有搜索引擎，优先从localStorage读取保存的搜索引擎ID
            if (searchEngines.length > 0) {
                // 先从localStorage读取保存的搜索引擎ID
                const savedEngineId = localStorage.getItem(STORAGE_KEY);

                
                // 检查是否存在匹配的搜索引擎，注意类型转换
                let foundMatch = false;
                if (savedEngineId) {
                    for (let i = 0; i < searchEngines.length; i++) {
                        const engine = searchEngines[i];
                        const engineIdStr = String(engine.id);
                        const savedIdStr = String(savedEngineId);
                        
                        if (engineIdStr === savedIdStr) {
                            currentSearchEngineId = engineIdStr;
                            foundMatch = true;

                            break;
                        }
                    }
                }
                
                if (!foundMatch) {
                    // 如果没有保存的ID或ID不存在，选择第一个
                    const firstEngineId = String(searchEngines[0].id);
                    currentSearchEngineId = firstEngineId;
                    // 保存默认选择到localStorage
                    localStorage.setItem(STORAGE_KEY, currentSearchEngineId);

                }
                
                // 确保DOM更新完成后再渲染图标
                setTimeout(() => {
                    try {

                        renderCurrentSearchEngineIcon();

                    } catch (error) {

                    }
                }, 0);
            } else {
    
            }
            
            // 返回搜索引擎列表，以便调用者可以使用
            return searchEngines;
        } else {
    
        }
    } catch (error) {

    }
    // 发生错误时返回空数组
    return [];
}

/**
 * 渲染当前选中的搜索引擎图标
 */
function renderCurrentSearchEngineIcon() {

    
    // 从localStorage读取，确保使用最新保存的值
    const savedEngineId = localStorage.getItem(STORAGE_KEY);
    if (savedEngineId) {
        currentSearchEngineId = savedEngineId; // 确保全局变量与localStorage同步

    }
    
    // 找到当前选中的搜索引擎，进行严格的字符串类型比较
    const engineIdStr = String(currentSearchEngineId);

    
    let currentEngine = null;
    for (let i = 0; i < searchEngines.length; i++) {
        const engine = searchEngines[i];
        if (String(engine.id) === engineIdStr) {
            currentEngine = engine;
            break;
        }
    }
    
    // 如果没有找到匹配的引擎，使用第一个
    if (!currentEngine && searchEngines.length > 0) {
        currentEngine = searchEngines[0];
        
    }
    

    
    // 获取图标容器
    const iconContainer = document.getElementById('current-search-engine-icon');
    if (!iconContainer) {
        return;
    }
    
    // 确保图标有点击事件
    iconContainer.onclick = toggleSearchEngineDropdown;
    
    // 强制清空图标容器 - 更严格的清空逻辑

    
    // 首先移除所有子元素
    while (iconContainer.firstChild) {
        iconContainer.removeChild(iconContainer.firstChild);
    }
    
    // 对于所有类型的容器，重置样式
    iconContainer.style.backgroundImage = 'none';
    iconContainer.style.background = 'transparent';
    
    // 特殊处理img元素
    if (iconContainer.tagName && iconContainer.tagName.toLowerCase() === 'img') {
        iconContainer.src = '';
        iconContainer.alt = '';
        iconContainer.removeAttribute('src');
        iconContainer.removeAttribute('alt');
    }
    
    // 确保容器内容完全清空
    iconContainer.innerHTML = '';
    
    // 延迟设置新图标，确保完全清空后再设置
    setTimeout(() => {
        // 如果有有效的搜索引擎和图标
        if (currentEngine && currentEngine.icon) {
            
            
            // 设置title显示搜索引擎名称
            iconContainer.title = currentEngine.name;
            
            if (iconContainer.tagName && iconContainer.tagName.toLowerCase() === 'img') {
                // 直接设置img元素的src
                iconContainer.src = currentEngine.icon;
                iconContainer.alt = currentEngine.name;
                iconContainer.style.display = 'block';
            } else {
                // 对于非img容器，创建新的img元素
                const img = document.createElement('img');
                img.src = currentEngine.icon;
                img.alt = currentEngine.name;
                img.style.width = '24px';
                img.style.height = '24px';
                img.style.objectFit = 'contain';
                img.style.margin = '0';
                img.style.padding = '0';
                img.style.border = 'none';
                img.style.outline = 'none';
                
                // 添加新图片
                iconContainer.appendChild(img);
            }
        }
        
        // 确保选择器也有点击事件
        const selector = document.querySelector('.search-engine-selector');
        if (selector) {
            selector.onclick = toggleSearchEngineDropdown;
        }
        

    }, 0);
}

/**
 * 渲染搜索引擎下拉菜单
 * @param {Array} engines - 搜索引擎列表
 * @param {number} currentId - 当前选中的搜索引擎ID
 */
function renderSearchEngineDropdown(searchEnginesData, currentId) {

    
    try {
        // 获取下拉菜单元素
        const dropdown = document.getElementById('search-engine-dropdown');
        if (!dropdown) {
        return;
    }
        
        // 设置下拉菜单为横向布局 - 保留毛玻璃效果
        dropdown.style.display = 'flex';
        dropdown.style.flexDirection = 'row';
        dropdown.style.flexWrap = 'nowrap';
        dropdown.style.justifyContent = 'flex-start';
        dropdown.style.alignItems = 'center';
        dropdown.style.gap = '8px';
        // 保留毛玻璃效果，不再重置背景和边框样式
        dropdown.style.outline = 'none';
        
        // 确保有搜索引擎数据
        const engines = searchEnginesData || window.searchEngines || [];
        let currentEngineId = currentId !== undefined ? currentId : window.currentSearchEngineId;
        
        // 确保使用最新的保存值
        const savedId = localStorage.getItem(STORAGE_KEY);
        if (savedId) {
            currentEngineId = savedId;
            currentSearchEngineId = savedId; // 同步更新全局变量
        }
        
        // 清空下拉菜单
        dropdown.innerHTML = '';
        
        if (!Array.isArray(engines) || engines.length === 0) {
    
            return;
        }
        
        // 移除固定大小设置，让菜单根据内容自动调整大小
        dropdown.style.width = 'auto';
        dropdown.style.height = 'auto';
        


        
        // 为每个搜索引擎创建选项
        engines.forEach(engine => {
            try {
                const option = document.createElement('div');
                option.className = 'search-engine-item' + (engine.id === currentEngineId ? ' active' : '');
                option.style.display = 'flex';
                option.style.alignItems = 'center';
                option.style.justifyContent = 'center';
                option.style.width = 'auto';
                option.style.height = 'auto';
                option.style.cursor = 'pointer';
                option.style.transition = 'background-color 0.2s';
                option.style.padding = '4px';
                option.style.margin = '0';
                option.style.backgroundColor = 'transparent';
                option.style.background = 'transparent';
                option.style.backdropFilter = 'none';
                option.style.borderRadius = '4px';
                option.style.border = 'none';
                option.style.boxShadow = 'none';
                option.style.outline = 'none';
                option.style.backgroundImage = 'none';
                
                // 设置title显示搜索引擎名称
                option.title = engine.name;
                
                // 创建图标
                const icon = document.createElement('img');
                icon.src = engine.icon || '/static/images/default-engine-icon.png';
                icon.alt = engine.name;
                icon.style.width = '24px';
                icon.style.height = '24px';
                icon.style.objectFit = 'contain';
                icon.style.margin = '0';
                icon.style.backgroundColor = 'transparent';
                icon.style.background = 'transparent';
                icon.style.backgroundImage = 'none';
                icon.style.border = 'none';
                icon.style.borderRadius = '0';
                icon.style.boxShadow = 'none';
                icon.style.outline = 'none';
                icon.style.backdropFilter = 'none';
                
                option.appendChild(icon);
                
                // 添加选中状态样式
                if (engine.id === currentEngineId) {
                    option.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
                }
                
                // 添加点击事件
                option.onclick = (e) => {
                    if (e && e.stopPropagation) e.stopPropagation();

                    const engineIdStr = String(engine.id);
                    currentSearchEngineId = engineIdStr;
                    localStorage.setItem(STORAGE_KEY, engineIdStr);
                    
                    // 强制重新渲染搜索引擎图标
                    setTimeout(() => {
                        renderCurrentSearchEngineIcon();
                    }, 0);
                    
                    // 隐藏下拉菜单
                    if (dropdown) {
                        dropdown.style.display = 'none';
                        window.dropdownVisible = false;
                    }
                };
                
                // 添加悬停效果
                option.addEventListener('mouseenter', function() {
                    if (engine.id !== currentEngineId) {
                        this.style.backgroundColor = 'transparent';
                    }
                });
                
                option.addEventListener('mouseleave', function() {
                    if (engine.id !== currentEngineId) {
                        this.style.backgroundColor = 'transparent';
                    }
                });
                
                dropdown.appendChild(option);
            } catch (error) {
            }
        });
    } catch (error) {
    }
}

/**
 * 切换搜索引擎下拉菜单显示/隐藏
 */
async function toggleSearchEngineDropdown(e) {
    try {
        
        // 阻止冒泡
        if (e && typeof e.stopPropagation === 'function') {
            e.stopPropagation();
        }
        
        // 检查searchEngines状态
        
        // 确保搜索引擎数据已加载
        if (!Array.isArray(searchEngines) || searchEngines.length === 0) {
    
            try {
                await loadSearchEngines();
        
                
                // 如果加载后仍然为空，直接返回
                if (!Array.isArray(searchEngines) || searchEngines.length === 0) {
            
                    return;
                }
            } catch (error) {
    
                return; // 如果加载失败，直接返回
            }
        }
        
        // 切换显示状态
        dropdownVisible = !dropdownVisible;
    
        
        // 获取图标元素作为定位参考
        const iconElement = document.getElementById('current-search-engine-icon');
        // 获取搜索框容器作为对齐参考
        const searchContainer = document.querySelector('.search-container');
    
        
        if (!iconElement || !searchContainer) {
            return;
        }
        
        // 确保下拉菜单存在，如果不存在则创建
        let dropdown = document.getElementById('search-engine-dropdown');
        if (!dropdown) {
        
            // 创建下拉菜单
            dropdown = document.createElement('div');
            dropdown.id = 'search-engine-dropdown';
            dropdown.className = 'search-engine-dropdown';
            
            // 设置下拉菜单样式 - 添加毛玻璃效果
            dropdown.style.position = 'absolute';
            dropdown.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
            dropdown.style.backdropFilter = 'blur(10px)';
            dropdown.style.webkitBackdropFilter = 'blur(10px)';
            dropdown.style.border = '1px solid rgba(255, 255, 255, 0.1)';
            dropdown.style.borderRadius = '8px';
            dropdown.style.boxShadow = '0 4px 15px rgba(0,0,0,0.2)';
            dropdown.style.zIndex = '1000';
            dropdown.style.padding = '8px';
            dropdown.style.overflow = 'hidden';
            dropdown.style.display = 'none'; // 初始隐藏
            
            // 添加到body
            document.body.appendChild(dropdown);
        
        }
        
        // 计算下拉菜单位置
        const iconRect = iconElement.getBoundingClientRect();
        const containerRect = searchContainer.getBoundingClientRect();
    
        // 设置下拉菜单位置（图标下方，左侧与搜索框对齐）
        dropdown.style.top = `${iconRect.bottom + window.scrollY + 4}px`;
        
        // 设置左侧与搜索框左侧对齐
        dropdown.style.left = `${containerRect.left + window.scrollX}px`;
        
        // 可选：限制宽度不超过搜索框
        dropdown.style.maxWidth = `${containerRect.width}px`;
        
        // 根据dropdownVisible状态设置显示/隐藏
        if (dropdownVisible) {
        
            // 重新渲染搜索引擎列表，确保使用最新数据
            renderSearchEngineDropdown(searchEngines, currentSearchEngineId);
            
            // 设置显示样式
            dropdown.style.display = 'flex';
            // 不设置flexDirection，让renderSearchEngineDropdown中的横向设置生效
        
            
            // 强制重排后保持左侧对齐
            setTimeout(() => {
                if (dropdown && searchContainer) {
                    const containerRect = searchContainer.getBoundingClientRect();
                    dropdown.style.left = `${containerRect.left + window.scrollX}px`;
                }
            }, 0);
            
            // 强制重排以解决Chrome和夸克浏览器兼容性问题
            dropdown.offsetHeight; // 触发重排
            
            // 添加点击外部关闭事件
            function handleClickOutside(event) {
                if (!dropdown.contains(event.target) && event.target !== iconElement) {
                    dropdown.style.display = 'none';
                    dropdownVisible = false;
                    document.removeEventListener('click', handleClickOutside);
                }
            }
            
            // 移除之前的事件监听器，避免重复
            document.removeEventListener('click', handleClickOutside);
            // 添加新的事件监听器
            document.addEventListener('click', handleClickOutside);
        } else {
            // 隐藏下拉菜单
            dropdown.style.display = 'none';
        
        }
    } catch (error) {
    }
}

/**
 * 点击外部关闭下拉菜单
 */
function closeDropdownOnOutsideClick(event) {
    const selector = document.querySelector('.search-engine-selector');
    const dropdown = document.getElementById('search-engine-dropdown');
    
    if (selector && dropdown && 
        !selector.contains(event.target) && 
        !dropdown.contains(event.target)) {
        dropdown.style.display = 'none';
        dropdownVisible = false;
        document.removeEventListener('click', closeDropdownOnOutsideClick);
    }
}

/**
 * 执行搜索
 * @param {string} query - 搜索关键词
 */
async function performSearchWithEngine(query) {
    // 确保搜索关键词有值
    if (!query || query.trim() === '') return;
    
    // 关键修复：如果搜索引擎数据未加载或为空，强制重新加载
    if (!searchEngines || searchEngines.length === 0) {
        await loadSearchEngines();
        
        // 如果加载后仍然为空，显示错误信息
        if (!searchEngines || searchEngines.length === 0) {
            alert('搜索引擎数据加载失败，请稍后重试');
            return;
        }
    }
    
    // 找到当前选中的搜索引擎，注意类型转换
    const engine = searchEngines.find(e => String(e.id) === String(currentSearchEngineId)) || searchEngines[0];
    
    // 确保engine对象存在且有url属性
    if (!engine || !engine.url) {
        return;
    }
    
    // 构建搜索URL
    const searchUrl = engine.url.replace('{query}', encodeURIComponent(query.trim()));
    
    // 检查URL是否有效
    try {
        // 使用单一方法打开新窗口，避免多次调用
        window.open(searchUrl, '_blank');
    } catch (error) {

    }
}

/**
 * 初始化搜索功能
 */
async function initSearch() {
    // 立即从localStorage读取保存的值，为loadSearchEngines做准备
    const savedEngineId = localStorage.getItem(STORAGE_KEY);
    if (savedEngineId) {
        currentSearchEngineId = savedEngineId;
    }
    
    // 确保图标容器存在，即使在搜索引擎数据加载前
    ensureSearchIconContainer();
    
    try {
        const engines = await loadSearchEngines();
    
        
        // 确保搜索引擎加载后重新渲染当前图标
        try {
            renderCurrentSearchEngineIcon();
        } catch (iconError) {
            // 即使图标渲染失败，也要继续设置搜索引擎选择器
        }
        
        // 确保搜索引擎选择器有正确的点击事件
        setupSearchEngineSelector();
    } catch (error) {
    }
}

/**
 * 确保搜索图标容器存在
 */
function ensureSearchIconContainer() {
    try {
        let iconContainer = document.getElementById('current-search-engine-icon');
        if (!iconContainer) {
            
            // 尝试找到搜索引擎选择器容器
            let selector = document.querySelector('.search-engine-selector');
        
            
            // 如果找不到selector或图标容器，创建一个新的图标容器
            if (selector && !iconContainer) {
                // 在selector中创建图标容器
                iconContainer = document.createElement('img');
                iconContainer.id = 'current-search-engine-icon';
                iconContainer.style.width = '24px';
                iconContainer.style.height = '24px';
                iconContainer.style.objectFit = 'contain';
                iconContainer.style.backgroundColor = 'transparent';
                iconContainer.style.cursor = 'pointer';
                
                // 添加到选择器中
                selector.appendChild(iconContainer);
            } else if (!selector) {
                // 如果完全没有选择器，创建一个基本的选择器和图标
                const searchInput = document.getElementById('search-input');
                if (searchInput && searchInput.parentNode) {
                
                    // 创建选择器容器div
                    selector = document.createElement('div');
                    selector.className = 'search-engine-selector';
                    selector.style.display = 'inline-flex';
                    selector.style.alignItems = 'center';
                    selector.style.justifyContent = 'center';
                    selector.style.backgroundColor = '#fff';
                    selector.style.border = '1px solid #ced4da';
                    selector.style.borderRight = 'none';
                    selector.style.borderTopLeftRadius = '0.375rem';
                    selector.style.borderBottomLeftRadius = '0.375rem';
                    selector.style.padding = '0 8px';
                    selector.style.height = '48px';
                    
                    // 创建图标容器
                    iconContainer = document.createElement('img');
                    iconContainer.id = 'current-search-engine-icon';
                    iconContainer.style.width = '24px';
                    iconContainer.style.height = '24px';
                    iconContainer.style.objectFit = 'contain';
                    iconContainer.style.backgroundColor = 'transparent';
                    iconContainer.style.cursor = 'pointer';
                    
                    // 添加图标到选择器
                    selector.appendChild(iconContainer);
                    
                    // 插入到搜索输入框之前
                    searchInput.parentNode.insertBefore(selector, searchInput);
                } else {

                    return null;
                }
            }
        }
        
        return iconContainer;
    } catch (error) {
        return null;
    }
}

/**
 * 设置搜索引擎选择器的点击事件
 */
function setupSearchEngineSelector() {
    // 获取搜索元素
    const searchEngineSelector = document.querySelector('.search-engine-selector');
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');
    
    // 设置搜索引擎选择器点击事件
    if (searchEngineSelector) {
        searchEngineSelector.onclick = function(e) {
            e.stopPropagation();
            toggleSearchEngineDropdown(e);
        };
    }
    
    // 设置搜索按钮样式和事件
    if (searchButton) {
        // 使用搜索图标替代文字
        searchButton.textContent = '🔍';
        searchButton.style.fontSize = '18px';
        searchButton.style.borderLeft = 'none'; // 确保没有左边框
        
        // 搜索按钮点击事件
        searchButton.onclick = async function(e) {
            e.stopPropagation();
            const query = searchInput ? searchInput.value.trim() : '';
            if (query) {
                await performSearchWithEngine(query);
            }
        };
    }
    
    // 设置搜索输入框样式和事件
    if (searchInput) {
        // 移除可能冲突的样式，使用HTML中定义的样式
        searchInput.style.padding = '0 16px'; // 保持一致的内边距
        
        // 确保搜索框容器样式正确
        const inputGroup = searchInput.closest('.input-group');
        if (inputGroup) {
            inputGroup.style.display = 'flex';
            inputGroup.style.alignItems = 'stretch';
        }
        
        // 设置Enter键搜索事件
        searchInput.addEventListener('keydown', async (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                e.stopPropagation();
                const query = searchInput.value.trim();
                if (query) {
                    await performSearchWithEngine(query);
                }
            }
        });
        
        // 移除可能的keypress事件，避免重复执行
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                e.stopPropagation();
            }
        });
        
        // 一键清除功能实现
        // 创建清除按钮
        let clearButton = document.getElementById('search-clear-button');
        if (!clearButton) {
            clearButton = document.createElement('button');
            clearButton.id = 'search-clear-button';
            clearButton.type = 'button';
            clearButton.innerHTML = '&times;'; // 使用×符号作为清除图标
            clearButton.title = '清除'; // 鼠标悬停提示
            
            // 设置清除按钮样式
            clearButton.style.position = 'absolute';
            clearButton.style.right = '40px'; // 位于搜索按钮左侧
            clearButton.style.top = '50%';
            clearButton.style.transform = 'translateY(-50%)';
            clearButton.style.width = '20px';
            clearButton.style.height = '20px';
            clearButton.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
            clearButton.style.border = 'none';
            clearButton.style.borderRadius = '50%';
            clearButton.style.color = '#fff';
            clearButton.style.fontSize = '14px';
            clearButton.style.lineHeight = '1';
            clearButton.style.cursor = 'pointer';
            clearButton.style.display = 'none'; // 默认隐藏
            clearButton.style.padding = '0';
            clearButton.style.margin = '0';
            clearButton.style.outline = 'none';
            clearButton.style.transition = 'all 0.2s ease';
            
            // 添加到搜索输入框的父容器
            const parentElement = searchInput.parentElement;
            if (parentElement) {
                parentElement.style.position = 'relative'; // 确保父容器为相对定位
                parentElement.appendChild(clearButton);
            }
        }
        
        // 清除按钮点击事件
        clearButton.onclick = function(e) {
            e.stopPropagation();
            searchInput.value = ''; // 清空输入框
            searchInput.focus(); // 保持输入框焦点
            clearButton.style.display = 'none'; // 隐藏清除按钮
        };
        
        // 监听输入框内容变化，控制清除按钮显示/隐藏
        function updateClearButtonVisibility() {
            if (searchInput.value.trim()) {
                clearButton.style.display = 'flex';
                clearButton.style.alignItems = 'center';
                clearButton.style.justifyContent = 'center';
            } else {
                clearButton.style.display = 'none';
            }
        }
        
        // 绑定输入事件
        searchInput.addEventListener('input', updateClearButtonVisibility);
        
        // 初始状态检查
        updateClearButtonVisibility();
        
        // 失焦时也更新按钮状态
        searchInput.addEventListener('blur', updateClearButtonVisibility);
        
        // 聚焦时也更新按钮状态
        searchInput.addEventListener('focus', updateClearButtonVisibility);
        
        // 查找搜索表单并阻止其默认提交行为
        const searchForm = searchInput ? searchInput.closest('form') : null;
        if (searchForm) {
            searchForm.onsubmit = async function(e) {
                // 阻止表单默认提交
                e.preventDefault();
                e.stopPropagation();
                // 手动执行搜索
                const query = searchInput ? searchInput.value.trim() : '';
                if (query) {
                    await performSearchWithEngine(query);
                }
                return false;
            };
        }
    }
}

// 页面加载完成后初始化搜索功能
document.addEventListener('DOMContentLoaded', initSearch);